//
//  AppDelegate.swift
//  maosheng
//
//  Created by 何海涛 on 2019/7/30.
//

import UIKit
import MapKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var rootViewController : TabBarController?
    var locaManager : CLLocationManager?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        if #available(iOS 11.0, *) {
            UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
        }
//        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5, execute: {
            //开启定位
            self.startUpdatingLocation()
//        })
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = .white
        window!.makeKeyAndVisible()
        LaunchSettings.applyGlobalAppearance()
        createRootViewController()
//        window!.rootViewController = Bootstrapper.createRootViewController()
        
//        self.locaManager = CLLocationManager()
//        //使用应用程序期间允许访问位置数据
//        locaManager?.requestWhenInUseAuthorization()
//        locaManager?.requestAlwaysAuthorization()
//        locaManager?.delegate = self
//        locaManager?.desiredAccuracy = kCLLocationAccuracyBest
     
        return true
    }
    func createRootViewController(){
        if UserInfo.getUserIsLogged() {
            let home = HomeViewController()
            home.str_title = "首页"
            let nav_home = UINavigationController(rootViewController: home)
     
            let nav_person = UINavigationController(rootViewController: PersonViewController())
            
            rootViewController = TabBarController(tabBarControllertabBarHeightWithImages: [UIImage(named: "main_icon_1"),UIImage(named: "main_icon_5") as Any], withHightLightImages: [UIImage(named: "main_icon_11") as Any,UIImage(named: "main_icon_55")], withTitles: ["首页","我的"], with: [nav_home,nav_person])
            
            window!.rootViewController = rootViewController

//            return  UINavigationController(rootViewController: HomeViewController())
            
        }else{
            let login = LoginViewController()
            let nav = UINavigationController(rootViewController: login)
            window!.rootViewController = nav
        }
    }
    func startUpdatingLocation() {
        if CLLocationManager.locationServicesEnabled(){
//            locaManager?.startUpdatingLocation()
            let map = MapManager.shareInstance() as? MapManager
            map!.getCurrentLocation()
        } else {
            //tell view controllers to show an alert
          
            self.showTurnOnLocationServiceAlert()
        }
        
     
    }
    func showTurnOnLocationServiceAlert()  {
        PublicTools.showAlert(currentVC: window!.rootViewController, meg: "请您开启定位方便为您推荐当地资讯", cancelBtn: "取消", otherBtn: "确定") { (action) in
            let settingsUrl = URL(string: UIApplication.openSettingsURLString)
            if let url = settingsUrl {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

extension AppDelegate :CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        print(NSLocale.isoCountryCodes)
        if let newLoca = locations.last {
            PLUserDefult.set(newLoca.coordinate.latitude, forKey: Latitude)
            PLUserDefult.set(newLoca.coordinate.longitude, forKey: Longitude)

            CLGeocoder().reverseGeocodeLocation(newLoca, completionHandler: { (pms, err) -> Void in
                if let newCoordinate = pms?.last?.location?.coordinate {
                    
                    manager.stopUpdatingLocation()//停止定位，节省电量，只获取一次定位
                    
                    let currentCoordinate = newCoordinate//记录定位点经纬度
                    print("\(currentCoordinate.latitude)")
                    
                    //取得最后一个地标，地标中存储了详细的地址信息，注意：一个地名可能搜索出多个地址
                    let placemark:CLPlacemark = (pms?.last)!
                    let location = placemark.location;//位置
                    let region = placemark.region;//区域
                    let addressDic = placemark.addressDictionary;//详细地址信息字典,包含以下部分信息
                    //                    let name=placemark.name;//地名
                    //                    let thoroughfare=placemark.thoroughfare;//街道
                    //                    let subThoroughfare=placemark.subThoroughfare; //街道相关信息，例如门牌等
                    //                    let locality=placemark.locality; // 城市
                    //                    let subLocality=placemark.subLocality; // 城市相关信息，例如标志性建筑
                    //                    let administrativeArea=placemark.administrativeArea; // 州
                    //                    let subAdministrativeArea=placemark.subAdministrativeArea; //其他行政区域信息
                    //                    let postalCode=placemark.postalCode; //邮编
                    //                    let ISOcountryCode=placemark.ISOcountryCode; //国家编码
                    //                    let country=placemark.country; //国家
                    //                    let inlandWater=placemark.inlandWater; //水源、湖泊
                    //                    let ocean=placemark.ocean; // 海洋
                    //                    let areasOfInterest=placemark.areasOfInterest; //关联的或利益相关的地标
                    print(location ?? 1111,region ?? 1111,addressDic ?? 111)
                }
            })
        }
    }
    
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        
        if (error as NSError).domain == kCLErrorDomain && (error as NSError).code == CLError.Code.denied.rawValue {
            //User denied your app access to location information.
            showTurnOnLocationServiceAlert()
        }
        
    }
    

}
